package com.cloudpivot.receivales.workorder.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.meta.view.ResponseMetaEnum;
import com.cloudpivot.receivales.workorder.domain.*;
import com.cloudpivot.receivales.workorder.service.WorkorderPoiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * 工单报告 对外接口
 */
@Controller
@RequestMapping("/workOrderReport")
@Slf4j
public class ReportController {

    @Value("${workorder.modepath}")
    private String MODEPATH;

    @Autowired
    private WorkorderPoiService service;

    /**
     * 测试用downlaod
     * @param response
     */
    @RequestMapping("/reportDownloadForTest")
    public void downloadForTest(HttpServletResponse response) {
        try {
            Map<String,Object> rspMap=service.createWorkorderStreamBySignbase64(null,null);
            if(Objects.isNull(rspMap)){
                return;
            }
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(rspMap.get("fileName").toString()));
            response.setContentType("application/octet-stream");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write((byte[]) rspMap.get("bytes"));
            outputStream.flush();
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 请求 创建 工单模版
     * @param entity
     * crmid:
     * refid:
     */
    @PostMapping ("/reportDownloadByCrmId")
    @ResponseBody
    public WorkorderReportRspDTO downloadReportByCrmId(@RequestBody JSONObject entity){
        try {
            //if (StringUtils.isBlank(entity.getString("crmid")) || StringUtils.isBlank(entity.getString("refid"))) {
            if (StringUtils.isBlank(entity.getString("crmid"))) {
                return new WorkorderReportRspDTO(-1,null);
            }else{
                WorkorderReportDTO reportDTO = service.getWorkOrderDetail(entity.getString("crmid"));
                Map<String,Object> rspMap = service.createWorkorderStreamBySignbase64(reportDTO,entity.getString("refid"));
                Base64.Encoder encoder = Base64.getEncoder();
                String base64 = encoder.encodeToString((byte[]) rspMap.get("bytes"));
                log.info("返回 base64 长度{}", base64.length());
                //本地放一份(上线后要取消)
//                byte[] _bytes = Base64.getDecoder().decode(base64);
//                BufferedOutputStream bos=null;
//                FileOutputStream fos=null;
//                File file=new File(MODEPATH+"out/test.docx");
//                fos = new FileOutputStream(file);
//                bos = new BufferedOutputStream(fos);
//                bos.write(_bytes);
                return new WorkorderReportRspDTO(1, base64);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new WorkorderReportRspDTO(-99,null);
        }
    }
    /**
     * 生成技术工单
     * @param entity
     * crmid:
     * refid:
     */
    @PostMapping ("/generateTechnicalWork")
    @ResponseBody
    public JSONObject generateTechnicalWork(@RequestBody JSONObject entity){
        JSONArray array = new JSONArray();
        try {
            if (StringUtils.isBlank(entity.getString("id")) || StringUtils.isBlank(entity.getString("signid"))) {
                log.info("对象空,无法转换");
                return resultJson(-1, null);
            }else{
                if (entity.getString("site_signature").equals("否")){
                    return resultJson(0, null);
                }
                TechnicalWorkDTO reportDTO = JSON.parseObject(entity.toString(), TechnicalWorkDTO.class);

                Map<String,Object> rspMap = service.createTechnicalWorkBySignbase64(reportDTO);
                Base64.Encoder encoder = Base64.getEncoder();
                String base64 = encoder.encodeToString((byte[]) rspMap.get("bytes"));
                log.info("返回 base64 长度{}", base64.length());
                JSONObject resJson = new JSONObject();
                resJson.put("fileNewName", "服务报告单"+reportDTO.getSequenceNo() + ".pdf");
                resJson.put("fileBase64", base64);
                log.info("文档处理完成");
                return resultJson(0, resJson);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return resultJson(-3, null);
        }
    }

    /**
     * 添加技术工单附件
     * @param entity
     * crmid:
     * refid:
     */
    @PostMapping ("/addTechnicalWorkAnnotations")
    @ResponseBody
    public JSONObject addTechnicalWorkAnnotations(@RequestBody JSONObject entity){
        try {
            if (StringUtils.isBlank(entity.getString("fileBase64")) || StringUtils.isBlank(entity.getString("guid"))) {
                log.info("对象空,无法转换");
                return null;
            }else{
                String ret =service.addTechnicalWorkAnnotations(entity.getString("fileBase64"),entity.getString("guid"));
                log.info("文档处理完成");
                JSONObject resJson = new JSONObject();
                resJson.put("fileNewName", "服务报告单.pdf");
                resJson.put("fileBase64", entity.getString("fileBase64"));
                return resultJson(0,resJson);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



    /**
     * 归档按钮接口（接收bpm）
     * crmid:
     * refid:
     * @return
     */
    @PostMapping("/putOnReportByCrmId")
    @ResponseBody
    public RspReportDTO putOnReportFile(@RequestBody JSONObject entity) {
        try {
            if (StringUtils.isBlank(entity.getString("crmid")) || StringUtils.isBlank(entity.getString("refid"))) {
                return new RspReportDTO(-2);
            }else{
                String crmid = entity.getString("crmid");
                String refid = entity.getString("refid");
                //获取crm对象+签名
                WorkorderReportDTO reportDTO = service.getWorkOrderDetail(crmid);
                Map<String,Object> rspMap = service.createWorkorderStreamBySignbase64(reportDTO,refid);
                Base64.Encoder encoder = Base64.getEncoder();
                String base64 = encoder.encodeToString((byte[]) rspMap.get("bytes"));
                log.info("返回 base64 长度{}", base64.length());
                //是否已经存在工单
                RspReportDTO<AnnotaionsDTO> rsp=service.getWorkOrderAnnotations(crmid);
                if (rsp.getCode() == 1) {
                    //已经存在 需要删除
                    String annGuid = rsp.getData().getAnnotationid();
                    //删除
                    service.delWorkOrderAnnotations(annGuid);
                } else if (rsp.getCode() == -1) {
                    //多个已经存在的 电子签名工单，手动处理
                    return new RspReportDTO(-1);
                }
                //保存到crm 工单中
                String ret=service.addWorkOrderAnnotations(base64, crmid);
                Map<String, String> _map = new HashMap<>();
                _map.put("guid", ret);
                log.info("保存工单：{}", ret);

                return new RspReportDTO(10,_map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new RspReportDTO(-9999);
        }
    }


    //--------------------------------------------------------------------------
    //以下数据为测试用
    private WorkorderReportDTO getEntity() throws Exception{
        //创建 模版替换对象
        WorkorderReportDTO entity = new WorkorderReportDTO();
        entity.setNew_num("Test-1001-0101");
        entity.setNew_accountname("测试的客户");
        entity.setNew_actual_problem_description("测试的描述");
        //子表
        WorkorderReportDTO.WxItem item = new WorkorderReportDTO.WxItem();
        item.setNew_name("Test");
        item.setNew_add_code("10001");
        item.setNew_productname("testProduct");
        item.setNew_number("1");
        List<WorkorderReportDTO.WxItem> wxlist = new ArrayList<>();
        wxlist.add(item);

        entity.setWxItems(wxlist);
        return entity;
    }

    private JSONObject resultJson(Integer code, JSONObject json) {

        JSONObject resJson = new JSONObject();
        resJson.put("code", code);
        resJson.put("msg", ResponseMetaEnum.getValue(code));
        resJson.put("result", json);
        return resJson;

    }
}
